<template>
	<div :class="['app-editor-container', 'app-span', `app-span-${name}`]">
		<span v-if="DataTypeUtil.isDate(dataTypeValue)">{{ getFormatDate() }}</span>
		<span v-else-if="textFormat" v-html="getFormatData()"></span>
		<div
			v-else-if="
				editorType == 'PICTURE' ||
				editorType == 'PICTURE_ONE' ||
				editorType == 'FILEUPLOADER'
			"
		>
			<a
				v-for="file in fileList"
				@click.stop.prevent="onDownload(file)"
				:key="file"
				>{{ file.name }}</a
			>
		</div>
		<span v-else>{{ text }}{{ unitName }}</span>
	</div>
</template>

<script setup lang="ts">
import { spanProps } from './span';
import { onBeforeMount, ref, Ref } from 'vue';
import { isExistAndNotEmpty, DataTypeUtil } from '@/core';
import { handleEditorNavParams, getDownloadUrl } from '@/hooks/use-editor';
import { IParam } from '@/core';
import { format, isEmpty } from '@/core';
import { format as formatFns, parseISO } from 'date-fns';
import { Http } from '@/http/http';
const props = defineProps(spanProps);
const { navContext, navViewParam } = handleEditorNavParams(props);
//  数据类型
const dataTypeValue = computed(() => {
	return DataTypeUtil.toString(props.dataType);
});
let text: Ref<string> = ref('');
let textFormat: Ref<string> = ref('');
const fileList: Ref<any[]> = ref([]);
const downloadUrl = getDownloadUrl(); //文件下载基础路径
//  初始化值
const initText = async () => {
	if (props.codeListTag) {
		const result = await App.getAppCodeListHelper().getCodeListItems(
			props.codeListTag,
			navContext,
			navViewParam
		);
		if (result.ok) {
			const item: IParam | undefined = result.data.find((item: any) =>
				Object.is(item.value, props.value)
			);
			if (item) {
				text.value = item.text;
			} else {
				text.value = props.value as string;
			}
		}
	} else if (
		props.editorType == 'PICTURE' ||
		props.editorType == 'PICTURE_ONE' ||
		props.editorType == 'FILEUPLOADER'
	) {
		if (props.value && typeof props.value == 'object') {
			fileList.value = props.value.fileList;
			if (fileList.value && fileList.value.length > 0) {
				fileList.value.forEach((file: any) => {
					let url = `${downloadUrl}/${file.response.id}`;
					file.url = url;
				});
			}
		}
	} else if (props.editorType === 'ADDRESSPICKUP') {
		if (isEmpty(props.value)) {
			text.value = '';
		} else {
			JSON.parse(`${props.value}`).forEach((item: any, index: number) => {
				text.value += index === 0 ? item.srfmajortext : ',' + item.srfmajortext;
			});
		}
	} else if (
		!props.value &&
		props.value !== 0 &&
		!props.unitName &&
		Object.is('STYLE1', props.noValueShowMode)
	) {
		text.value = '---';
	} else {
		text.value = props.value as string;
	}
	if (props.valueFormat) {
		textFormat.value = props.valueFormat;
	} else if (DataTypeUtil.isDate(dataTypeValue.value)) {
		textFormat.value = 'yyyy-MM-dd HH:mm:ss';
	} else if (DataTypeUtil.isNumber(dataTypeValue.value)) {
		textFormat.value = `#${props.unitName}`;
	}
};

//  获取格式化数据
const getFormatData = () => {
	if (!isExistAndNotEmpty(`${props.value}`)) {
		return '';
	}
	let value: any = props.value;
	try {
		if (DataTypeUtil.isNumber(dataTypeValue.value)) {
			let number: any = Number(value);
			const decimalCnt: number =
				value?.toString()?.split('.').length > 1
					? value.toString().split('.')[1].length
					: 0;
			value =
				props.precision === 0 && decimalCnt !== 0
					? number.toFixed(decimalCnt)
					: number.toFixed(props.precision);
		}
		value = format.format(value, textFormat.value);
	} catch (error) {
		console.error(error);
	}
	return value;
};

//  获取格式化日期
const getFormatDate = () => {
	if (!isExistAndNotEmpty(`${props.value}`)) {
		return '';
	}
	if (props.value && typeof props.value === 'string') {
		try {
			const tempFormat = textFormat.value
				.replaceAll('Y', 'y')
				.replaceAll('D', 'd');
			const value = formatFns(parseISO(props.value), tempFormat);
			if (value) {
				return value;
			}
		} catch (error) {
			return props.value;
		}
	}
	return props.value;
};

onBeforeMount(() => {
	//  监听值变化
	watch(
		() => props.value,
		(newVal: any, oldVal: any) => {
			if (newVal !== oldVal) initText();
		}
	);
	initText();
});

const onDownload = (file: any) => {
	//下载文件
	DownloadFile(file.url, file);
};

//下载文件
const DownloadFile = async (url: string, file: any) => {
	// 发送get请求
	const downloaderror = App.ts('common.fileupload.downloaderror', '下载失败');
	try {
		const response = await Http.getHttp()({
			method: 'get',
			url: url,
			responseType: 'blob',
		});
		if (!response || response.status != 200) {
			App.getNotificationHelper().warning(downloaderror);
			return;
		}
		// 请求成功，后台返回的是一个文件流
		if (response.data) {
			// 获取文件名
			const filename = file.name;
			const ext = '.' + filename.split('.').pop();
			let filetype = calcFilemime(ext);
			// 用blob对象获取文件流
			let blob = new Blob([response.data], { type: filetype });
			// 通过文件流创建下载链接
			var href = URL.createObjectURL(blob);
			// 创建一个a元素并设置相关属性
			let a = document.createElement('a');
			a.href = href;
			a.download = filename;
			// 添加a元素到当前网页
			document.body.appendChild(a);
			// 触发a元素的点击事件，实现下载
			a.click();
			// 从当前网页移除a元素
			document.body.removeChild(a);
			// 释放blob对象
			URL.revokeObjectURL(href);
		} else {
			App.getNotificationHelper().warning(downloaderror);
		}
	} catch (error) {
		App.getNotificationHelper().warning(downloaderror);
	}
};
//计算文件类型
const calcFilemime = (filetype: string): string => {
	let mime = 'image/png';
	switch (filetype) {
		case '.wps':
			mime = 'application/kswps';
			break;
		case '.doc':
			mime = 'application/msword';
			break;
		case '.docx':
			mime =
				'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
			break;
		case '.txt':
			mime = 'text/plain';
			break;
		case '.zip':
			mime = 'application/zip';
			break;
		case '.png':
			mime = 'imgage/png';
			break;
		case '.gif':
			mime = 'image/gif';
			break;
		case '.jpeg':
			mime = 'image/jpeg';
			break;
		case '.jpg':
			mime = 'image/jpeg';
			break;
		case '.rtf':
			mime = 'application/rtf';
			break;
		case '.avi':
			mime = 'video/x-msvideo';
			break;
		case '.gz':
			mime = 'application/x-gzip';
			break;
		case '.tar':
			mime = 'application/x-tar';
			break;
	}
	return mime;
};
</script>
